import {
  Directive,
  OnInit,
  OnDestroy,
  Input,
  Output,
  HostListener,
  EventEmitter,
  AfterViewInit,
  ElementRef,
} from "@angular/core";
import { interval, Subject, Subscription } from "rxjs";
import { throttle } from "rxjs/operators";

@Directive({
  selector: "[appThrottle]",
})
export class ThrottleDirective implements OnInit, AfterViewInit, OnDestroy {
  @Input() onClickTime = 500;
  @Output() onClick = new EventEmitter();
  private clicks = new Subject<any>();
  constructor(
    private subscription: Subscription,
    private elementRef: ElementRef
  ) {}

  ngOnInit() {
    this.subscription = this.clicks
      .pipe(throttle((e) => interval(this.onClickTime)))
      .subscribe((res) => this.onClick.emit(this.elementRef));
  }

  ngAfterViewInit() {
    this.elementRef.nativeElement.tabIndex = "-1";
  }

  ngOnDestroy() {
    this.subscription && this.subscription.unsubscribe();
  }

  @HostListener("click", ["$event"])
  clickEvent(event: Event) {
    event.preventDefault();
    // 防止冒泡事件
    event.stopPropagation();
    this.clicks.next(event);
  }
}
